package com.mfw.springboot.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mfw.springboot.common.DataGroupByDateDTO;
import com.mfw.springboot.common.ErrorCode;
import com.mfw.springboot.constant.CommonConstant;
import com.mfw.springboot.exception.ThrowUtils;
import com.mfw.springboot.mapper.ClassInfoMapper;
import com.mfw.springboot.model.dto.classInfo.ClassInfoQueryRequest;
import com.mfw.springboot.model.entity.ClassInfo;
import com.mfw.springboot.model.entity.User;
import com.mfw.springboot.model.vo.ClassInfoVO;
import com.mfw.springboot.model.vo.UserVO;
import com.mfw.springboot.service.ClassInfoService;
import com.mfw.springboot.service.UserService;
import com.mfw.springboot.utils.DateUtils;
import com.mfw.springboot.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 班级服务实现
 *
 * @author mfw
 * @from <a href="https://gitee.com/hanhuaifei/projects">我的gitee</a>
 * @Date 2024/9/26
 */
@Service
@Slf4j
public class ClassInfoServiceImpl extends ServiceImpl<ClassInfoMapper, ClassInfo> implements ClassInfoService {

    @Resource
    private UserService userService;

    /**
     * 校验数据
     *
     * @param classInfo
     * @param add       对创建的数据进行校验
     */
    @Override
    public void validClassInfo(ClassInfo classInfo, boolean add) {
        ThrowUtils.throwIf(classInfo == null, ErrorCode.PARAMS_ERROR);
        // 从对象中取值
        String className = classInfo.getClassName();
        String description = classInfo.getDescription();

        // 创建数据时，参数不能为空
        if (add) {
            // 补充校验规则
            ThrowUtils.throwIf(StringUtils.isBlank(className), ErrorCode.PARAMS_ERROR);
        }
        // 修改数据时，有参数则校验
        // 补充校验规则
        if (StringUtils.isNotBlank(className)) {
            ThrowUtils.throwIf(className.length() > 20, ErrorCode.PARAMS_ERROR, "标题过长");
        }
        if (StringUtils.isNotBlank(description)) {
            ThrowUtils.throwIf(description.length() > 80, ErrorCode.PARAMS_ERROR, "描述过长");
        }
    }

    /**
     * 获取查询条件
     *
     * @param classInfoQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<ClassInfo> getQueryWrapper(ClassInfoQueryRequest classInfoQueryRequest) {
        QueryWrapper<ClassInfo> queryWrapper = new QueryWrapper<>();
        if (classInfoQueryRequest == null) {
            return queryWrapper;
        }
        // 从对象中取值
        Long id = classInfoQueryRequest.getId();
        String className = classInfoQueryRequest.getClassName();
        String description = classInfoQueryRequest.getDescription();
        Long userId = classInfoQueryRequest.getUserId();
        String status = classInfoQueryRequest.getStatus();

        String sortField = classInfoQueryRequest.getSortField();
        String sortOrder = classInfoQueryRequest.getSortOrder();


        //  补充需要的查询条件
        // 模糊查询
        queryWrapper.like(StringUtils.isNotBlank(className), "class_name", className);
        queryWrapper.like(StringUtils.isNotBlank(description), "description", description);

        // 精确查询
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "user_id", userId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(status), "status", status);
        // 排序规则
        queryWrapper.orderBy(SqlUtils.validSortField(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    /**
     * 获取班级封装
     *
     * @param classInfo
     * @param request
     * @return
     */
    @Override
    public ClassInfoVO getClassInfoVO(ClassInfo classInfo, HttpServletRequest request) {
        // 对象转封装类
        ClassInfoVO classInfoVO = ClassInfoVO.objToVo(classInfo);

        // 可以根据需要为封装对象补充值，不需要的内容可以删除
        // region 可选
        // 1. 关联查询用户信息
        Long userId = classInfo.getUserId();
        User user = null;
        if (userId != null && userId > 0) {
            user = userService.getById(userId);
        }
        UserVO userVO = userService.getUserVO(user);
        classInfoVO.setUser(userVO);
        // endregion

        return classInfoVO;
    }

    /**
     * 分页获取班级封装
     *
     * @param classInfoPage
     * @param request
     * @return
     */
    @Override
    public Page<ClassInfoVO> getClassInfoVOPage(Page<ClassInfo> classInfoPage, HttpServletRequest request) {
        List<ClassInfo> classInfoList = classInfoPage.getRecords();
        Page<ClassInfoVO> classInfoVOPage = new Page<>(classInfoPage.getCurrent(), classInfoPage.getSize(), classInfoPage.getTotal());
        if (CollUtil.isEmpty(classInfoList)) {
            return classInfoVOPage;
        }
        // 对象列表 => 封装对象列表
        List<ClassInfoVO> classInfoVOList = classInfoList.stream().map(classInfo -> {
            return ClassInfoVO.objToVo(classInfo);
        }).collect(Collectors.toList());

        // 可以根据需要为封装对象补充值，不需要的内容可以删除
        // region 可选
        // 1. 关联查询用户信息
        Set<Long> userIdSet = classInfoList.stream().map(ClassInfo::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 填充信息
        classInfoVOList.forEach(classInfoVO -> {
            Long userId = classInfoVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            classInfoVO.setUser(userService.getUserVO(user));
        });
        // endregion

        classInfoVOPage.setRecords(classInfoVOList);
        return classInfoVOPage;
    }

    /**
     * 分按日期分组查询班级新增数量
     *
     * @param beginDate 开始时间
     * @param endDate   结束时间
     * @return
     */
    @Override
    public List<DataGroupByDateDTO> countByDay(Date beginDate, Date endDate) {
        QueryWrapper<ClassInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("DATE_FORMAT(create_time, '%Y-%m-%d') AS day", "COUNT(1) AS num");
        queryWrapper.ge("create_time", beginDate);
        queryWrapper.le("create_time", endDate);
        queryWrapper.groupBy("day");
        queryWrapper.orderByAsc("day");
        // 执行查询
        List<Map<String, Object>> results = this.baseMapper.selectMaps(queryWrapper);
        // 映射到 DataGroupByDateDTO
        return results.stream().map(result -> {
            DataGroupByDateDTO dto = new DataGroupByDateDTO();
            dto.setDay(DateUtils.parse(result.get("day").toString(), DateUtils.FMT_YMD));
            dto.setNum((Long) result.get("num"));
            return dto;
        }).collect(Collectors.toList());
    }

}
